var iot = require('iot');
var network = require('network');

var net = network.openNetWorkClient();

var productKey = 'your productKey';      /* your productKey */
var deviceName = 'your deviceName';      /* your deviceName */
var deviceSecret = 'your deviceSecret';  /* your deviceSecret */

var device;

function createDevice()
{
    device = iot.device({
        productKey: productKey,
        deviceName: deviceName,
        deviceSecret: deviceSecret
    });
}

var topic = '/sys/'+ productKey + '/' + deviceName + '/user/haas/info';

device.on('connect', function () {
    console.log('(re)connected');

    device.subscribe({
        topic: topic,
        qos: 0
    });

    device.unsubscribe(topic);

    device.publish({
        topic: topic,
        payload: 'haas haas haas',
        qos: 1
    });

    var lightswitch = 0;
    var eventid = 'alarmEvent';
    var eventparams = '{\"alarmType\": 0}';
    
    setInterval(function() {
        if (lightswitch) {
            lightswitch = 0;
        } else {
            lightswitch = 1;
        }

        /* post props */
        device.postProps('{\"LightSwitch\": ' + lightswitch + '}');

        /* post event */
        device.postEvent({
            id: eventid,
            params: eventparams 
        });
    
    }, 3000);

    /* 云端设置属性事件 */
    device.onProps(function (res) {
        console.log('cloud req msg_id is ' + res.msg_id);
        console.log('cloud req params_len is ' + res.params_len);
        console.log('cloud req params is ' + res.params);
    });

    /* 云端下发服务事件 */
    device.onService(function (res) {
        console.log('received cloud msg_id is ' + res.msg_id);
        console.log('received cloud service_id is ' + res.service_id);
        console.log('received cloud params_len is ' + res.params_len);
        console.log('received cloud params is ' + res.params);
    });
});

/* 网络断开事件 */
device.on('disconnect', function () {
    console.log('disconnect ');
});

/* mqtt消息 */
device.on('message', function(res) {
    console.log('mqtt message')
    console.log('mqtt topic is ' + res.topic);
    console.log('mqtt payload is ' + res.payload);
})

/* 关闭连接事件 */
device.on('end', function () {
    console.log('iot client just closed');
});

/* 发生错误事件 */
device.on('error', function (err) {
    console.log('error ' + err);
});

var status = net.getStatus();
console.log('net status is: ' + status);

if (status == 'connect') {
    createDevice();
} else {
    net.on('connect', function () {
        createDevice();
    });
}